package org.example.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.example.exception.BusinessException;
import org.example.mapper.StudentMapper;
import org.example.pojo.PageResult;
import org.example.pojo.Student;
import org.example.pojo.StudentQueryParam;
import org.example.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper studentMapper;

    @Override
    public PageResult<Student> page(StudentQueryParam studentQueryParam) {
        // 1.设置分页查询的默认值
        PageHelper.startPage(studentQueryParam.getPage(), studentQueryParam.getPageSize());
        // 2.执行查询
        List<Student> studentList = studentMapper.page(studentQueryParam);

        // 3.返回查询结果
        Page<Student> page = (Page<Student>) studentList;
        return new PageResult<>(page.getTotal(), page.getResult());

    }

    /*
    * 新增学员
    * */
    @Override
    public void add(Student student) {
        // 1.补充参数的值
        student.setCreateTime(LocalDateTime.now());
        student.setUpdateTime(LocalDateTime.now());
        student.setViolationCount((short) 0);
        student.setViolationScore((short) 0);

        // 2.调用Mapper层接口
        studentMapper.add(student);
    }

    /*
    * 根据ID查询学生
    * */
    @Override
    public Student getById(Integer id) {
        // 直接调用返回
        return studentMapper.getById(id);
    }

    /*
    * 删除学生
    * */
    @Override
    public void deleteByIds(List<Integer> ids) {
        studentMapper.deleteByIds(ids);
    }

    /*
    * 处理违纪
    * */
    @Override
    public void processViolation(Integer id, Integer score) {
        // 1.查询学生信息
        Student student = studentMapper.getById(id);
        if (student == null) {
            throw new BusinessException("学生不存在");
        }

        // 2.处理违纪
        student.setViolationCount((short)(student.getViolationCount() + 1));
        student.setViolationScore((short)(student.getViolationScore() + score));
        student.setUpdateTime(LocalDateTime.now());

        // 3.更新
        studentMapper.updateViolation(student);
    }
}
